﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MAF.Common;
using System.IO;
using MAF.Json;

namespace Domain.Repository
{
    /// <summary>
    /// 内存存储类。
    /// </summary>
    /// <remarks>
    /// 说明：UI层可以重写Config类来改变存储方式。
    /// </remarks>
    public class Storage
    {
        public static IRepository<Note> MemNotes { get; internal set; }

        public static IRepository<Note> JsonNotes { get; internal set; }

        static Storage()
        {
            MemNotes = new MemRepo<Note>();

            JsonNotes = new JsonStorage();
        }
    }

    /// <summary>
    /// Json存储
    /// </summary>
    internal class JsonStorage : IRepository<Note>
    {
        private string _fileDir;

        public JsonStorage()
        {
            _fileDir = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Data");
        }

        public string GuidToBase64(Guid guid)
        {
            return Convert.ToBase64String(guid.ToByteArray())
                .Replace("/", "-")
                .Replace("+", "_")
                .Replace("=", "");
        }

        public Guid Base64ToGuid(string base64)
        {
            Guid guid = default(Guid);
            base64 = base64.Replace("-", "/").Replace("_", "+") + "==";

            try
            {
                guid = new Guid(Convert.FromBase64String(base64));
            }
            catch (Exception ex)
            {
                throw new Exception("Bad Base64 conversion to GUID", ex);
            }

            return guid;
        }

        private string GetFilePath(Guid id)
        {
            return Path.Combine(_fileDir, GuidToBase64(id));
        }

        public void Add(Note entity)
        {
            if (null == entity)
            {
                throw new ArgumentNullException("新增实体不能传入null参数");
            }
            File.WriteAllText(GetFilePath(entity.Id), JsonConvert.SerializeObject(entity));
        }

        public int Update(Note entity)
        {
            File.WriteAllText(GetFilePath(entity.Id), JsonConvert.SerializeObject(entity));
            return 1;
        }

        public int Update(List<Note> entities)
        {
            throw new NotImplementedException();
        }

        public int UpdateByQuery(Query<Note> q)
        {
            throw new NotImplementedException();
        }

        public int Remove(Guid id)
        {
            throw new NotImplementedException();
        }

        public int Remove(Note entity)
        {
            File.Delete(GetFilePath(entity.Id));
            return 1;
        }

        public int Remove(string ids)
        {
            throw new NotImplementedException();
        }

        public int Remove(List<Note> entities)
        {
            throw new NotImplementedException();
        }

        public int RemoveByQuery(Query<Note> q)
        {
            throw new NotImplementedException();
        }

        public Note GetById(Guid id)
        {
            var s = File.ReadAllText(GetFilePath(id));
            return JsonConvert.DeserializeObject<Note>(s);
        }

        public List<Note> GetByQuery(Query<Note> q)
        {
            List<Note> list = new List<Note>();
            if (!Directory.Exists(_fileDir))
                Directory.CreateDirectory(_fileDir);

            var files = Directory.GetFiles(_fileDir);
            foreach (string s in files)
            {
                list.Add(GetById(Base64ToGuid(Path.GetFileName(s))));
            }
            return list;
        }

        public int CountByQuery(Query<Note> q)
        {
            throw new NotImplementedException();
        }
    }

    /// <summary>
    /// 日志类
    /// </summary>
    internal class Logger
    {
        public static void Warn(string s)
        {
            throw new NotImplementedException("此类是个占位示范类，说明系统需要这个东西，还没有经过思考设计");
        }
    }
}